package xyz.thetbw.autocode.utils

import java.util.*
import java.util.regex.Matcher
import java.util.regex.Pattern

object StringCaseUtils {

    private val linePattern: Pattern = Pattern.compile("_(\\w)")
    private val humpPattern: Pattern = Pattern.compile("[A-Z]")

    /**
     * 下划线转驼峰
     */
    fun lineToHump(value: String): String {
        var str = value
        if (str.isBlank()) {
            return str
        }
        str = str.lowercase(Locale.getDefault())
        val matcher: Matcher = linePattern.matcher(str)
        val sb = StringBuffer()
        while (matcher.find()) {
            matcher.appendReplacement(sb, matcher.group(1).uppercase(Locale.getDefault()))
        }
        matcher.appendTail(sb)
        str = sb.toString()
        str = str.substring(0, 1).uppercase(Locale.getDefault()) + str.substring(1)
        return str
    }

    /**
     * 驼峰转下划线,效率比上面高
     */
    fun humpToLine(str: String): String {
        val matcher: Matcher = humpPattern.matcher(str)
        val sb = StringBuffer()
        while (matcher.find()) {
            matcher.appendReplacement(sb, "_" + matcher.group(0).lowercase(Locale.getDefault()))
        }
        matcher.appendTail(sb)
        return sb.toString()
    }


    /**
     * 首字母转大写
     */
    fun uppercaseFirst(value: String): String {
        if (value.isBlank()) {
            return value
        }
        return if (Character.isUpperCase(value[0]))  value else StringBuilder().append(Character.toUpperCase(value[0])).append(value.substring(1)).toString()
    }

    /**
     * object转String
     */
    fun getString(`object`: Any?): String? {
        return getString(`object`, "")
    }

    private fun getString(`object`: Any?, defaultValue: String?): String? {
        return if (null == `object`) {
            defaultValue
        } else try {
            `object`.toString()
        } catch (e: Exception) {
            defaultValue
        }
    }

    /**
     * 首字母转小写
     */
    fun lowercaseFirst(value: String): String {
        if (value.isBlank()) {
            return value
        }
        return if (Character.isLowerCase(value[0])) value else StringBuilder().append(Character.toLowerCase(value[0])).append(value.substring(1)).toString()
    }

}

